package org.ezplatform.office.meeting.setting.boardroom.web.rest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.ezplatform.cloud.api.component.popuser.PopUserScopeUtilService;
import org.ezplatform.cloud.api.system.user.UserApiService;
import org.ezplatform.cloud.common.client.RestClient;
import org.ezplatform.cloud.common.log.LogService;
import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.pagination.PropertyFilter;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.core.web.controller.BaseController;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.core.web.view.OperationResult;
import org.ezplatform.office.meeting.common.util.MeetingUtils;
import org.ezplatform.office.meeting.info.entity.MeetingScope;
import org.ezplatform.office.meeting.info.service.MeetingScopeService;
import org.ezplatform.office.meeting.info.web.rest.ApplyRecordWebApiController;
import org.ezplatform.office.meeting.setting.boardroom.entity.BoardroomSet;
import org.ezplatform.office.meeting.setting.boardroom.service.BoardroomSetService;
import org.ezplatform.office.meeting.setting.category.entity.BoardroomCategorySet;
import org.ezplatform.office.meeting.setting.category.service.BoardroomCategorySetService;
import org.ezplatform.office.meeting.setting.serve.entity.ServeSet;
import org.ezplatform.office.meeting.setting.serve.service.ServeSetService;
import org.ezplatform.util.JsonUtils;
import org.ezplatform.util.StringUtils;
import org.ezplatform.util.UuidUtils;
import org.ezplatform.util.ValidateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.drew.lang.StringUtil;

/**
 * @ClassName: OaMeetingBaseSetController
 * @Description: 会议室设置控制类
 */
@RestController
@RequestMapping(value = "/api/w/boardroomSetController")
public class BoardroomSetWebApiController extends BaseController<BoardroomSet, String> {
	private final static Logger LOGGER = LoggerFactory.getLogger(BoardroomSetWebApiController.class);
	
    private String msg = "";
    
	@Autowired
	private BoardroomSetService service;
	
	@Autowired
    private PopUserScopeUtilService popUserScopeUtilService;
	
	@Autowired
    private BoardroomCategorySetService boardroomCategorySetService;

	@Autowired
	private ServeSetService serveSetService;
	
	@Autowired
    private UserApiService userApiService;

    @Autowired
    private RestClient restClient;

    @Autowired
	private LogService logService;
    
    @Autowired
    private MeetingScopeService meetingScopeService;
    
	@Override
	protected BaseService<BoardroomSet, String> getEntityService() {
		return service;
	}

	/**
	 * 
	 * @Title: prepareModel
	 * @Description: 初始化数据
	 * @param request
	 * @param model
	 * @param id
	 * @return void
	 * @throws
	 */
	@ModelAttribute
	public void prepareModel(HttpServletRequest request, Model model,
			@RequestParam(value = "id", required = false) String id) {
		super.initPrepareModel(request, model, id);
	}

	/**
	 * 
	 * @Title: findByPage
	 * @Description: 获取列表数据（翻页）
	 * @param request
	 * @return
	 * @return PageOaMeetingBaseSet
	 * @throws
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	@RequiresPermissions({"meeting:room:03"})
	public Page findByPage(HttpServletRequest request) {
	    WebUser user = WebUtils.getCurrentUser();
        String corpId = user.getCorpId();
        Pageable localPageable = PropertyFilter.buildPageableFromHttpRequest(request);
        //名称
        String name = ValidateUtils.filter(request.getParameter("name"));
		return this.service.getBoardroomSetList(localPageable,corpId,name,user);
	}
	
	/**
     * 保存/修改
     *
     * @param entity
     * @param model
     * @return
     */
    @RequestMapping(value = "/editSave", method = RequestMethod.POST)
    public OperationResult editSave(@ModelAttribute("entity") BoardroomSet entity, Model model,HttpServletRequest request) {
    	LOGGER.debug("-----editSave----");
        String id = StringUtils.null2String(entity.getId());
        String oleName = "";
        if(StringUtils.isNotEmpty(id)) {
        	BoardroomSet bs = this.service.findOne(id);
        	oleName = bs.getName();
        }
        String name = entity.getName();
        WebUser user = WebUtils.getCurrentUser();
        String corpId = user.getCorpId();
        String token = user.getJwtToken();
        //保存前 验证
        // 验证名称
        msg = this.service.checkBoardroomSet(id, name, 1, corpId);
        if (StringUtils.isNotEmpty(msg)) {
            return OperationResult.buildFailureResult(msg);
        }
        // 管理员
        String jsonStr = StringUtils.null2String(request.getParameter("jsonStrAdminUserScope"));
        String adminUserScope = StringUtils.null2String(entity.getAdminUserScope());
        if ("".equals(adminUserScope)) {
            adminUserScope = UuidUtils.UUID();
            entity.setAdminUserScope(adminUserScope);
        }
        this.popUserScopeUtilService.saveScopeData("oa_meeting_apply_record_scope", adminUserScope, jsonStr,
                "oa_meeting_boardroom_set", "admin_user_scope");
        
        //适用范围
        String jsonStrscopeuse = StringUtils.null2String(request.getParameter("jsonStrscopeuse"));
        LOGGER.debug("-jsonStrscopeuse："+jsonStrscopeuse);
        LOGGER.debug("-entity.getScopeuseuser()："+entity.getScopeuseuser());
        if(jsonStrscopeuse!=null&&!"null".equals(jsonStrscopeuse)&&!"".equals(jsonStrscopeuse)) {
	        String scopeuse = StringUtils.null2String(entity.getScopeuseuser());
	        if ("".equals(scopeuse)) {
	        	scopeuse = UuidUtils.UUID();
	            entity.setScopeuseuser(scopeuse);
	        }
	        this.popUserScopeUtilService.saveScopeData("oa_meeting_apply_record_scope", scopeuse, jsonStrscopeuse,
	                "oa_meeting_boardroom_set", "scopeuse_user");
        }else {
        	entity.setScopeuseuser("");
        }
        //记录日志
  		if(StringUtils.isNotEmpty(id) && logService.checkOptLog(corpId, "meetingLog:room:02", token))//判断是否记录日志 
  			this.logService.saveModuleLog("meetingLog:room:02", oleName, "");  
  		else if(logService.checkOptLog(corpId, "meetingLog:room:01", token)) {
  			this.logService.saveModuleLog("meetingLog:room:01", name, "");
  		}
        return super.editSave(entity);
    }
	
    /**
     * 编辑页面
     * 
     * @param model
     * @return
     */
    @RequestMapping(value = "/editShow", method = RequestMethod.GET)
    public Map<String, Object> editShow(HttpServletRequest request) {
    	LOGGER.debug("-----editShow----");
        WebUser user = WebUtils.getCurrentUser();
        String corpId = "";
        if (user != null) {
            corpId = user.getCorpId();
        }
        String id = ValidateUtils.filter(request.getParameter("id"));
        Map<String, Object> result = new HashMap<>();
        
        BoardroomSet boardroomSet = this.service.findOne(id);
        result.put("entity", boardroomSet);
        
        // 适用范围
        String scopeuseUser = popUserScopeUtilService.getScopeTypeValue("oa_meeting_apply_record_scope", "oa_meeting_boardroom_set",
                "scopeuse_user", StringUtils.null2String(boardroomSet.getScopeuseuser()));
        LOGGER.debug("-scopeuseUser:"+scopeuseUser);
        result.put("scopeuseUser", scopeuseUser);
        
        // 管理员
        String adminUserScope = popUserScopeUtilService.getScopeTypeValue("oa_meeting_apply_record_scope",
                "oa_meeting_boardroom_set", "admin_user_scope", StringUtils.null2String(boardroomSet.getAdminUserScope()));
        result.put("adminUserScope", adminUserScope);
        if (StringUtils.isNotEmpty(adminUserScope)) {
            String scopeName = this.userApiService.getScopeName(adminUserScope, corpId, TOKEN);
            result.put("adminUserName", scopeName);
        }
        return result;
    }
    
    /**
     * 编辑页面
     * 
     * @param model
     * @return
     */
    @RequestMapping(value = "/viewBRPosition", method = RequestMethod.GET)
    public Map<String, Object> viewBRPosition(HttpServletRequest request) {
    	String id = ValidateUtils.filter(request.getParameter("id"));
    	Map<String, Object> result = new HashMap<>();
    	
    	BoardroomSet boardroomSet = this.service.findOne(id);
    	result.put("boardRoom", boardroomSet);
    	return result;
    }
    
    /**
     * 查看页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/viewShow", method = RequestMethod.GET)
    public Map<String, Object> viewShow(HttpServletRequest request) {
        WebUser user = WebUtils.getCurrentUser();
        String corpId = "";
        if (user != null) {
            corpId = user.getCorpId();
        }
        String id = ValidateUtils.filter(request.getParameter("id"));
        Map<String, Object> result = new HashMap<>();
        
        BoardroomSet boardroomSet = this.service.findOne(id);
        result.put("entity", boardroomSet);
        
     // 适用范围
        String scopeuseUser = popUserScopeUtilService.getScopeTypeValue("oa_meeting_apply_record_scope", "oa_meeting_boardroom_set",
                "scopeuse_user", StringUtils.null2String(boardroomSet.getScopeuseuser()));
        LOGGER.debug("-scopeuseUser:"+scopeuseUser);
        result.put("scopeuseUser", scopeuseUser);
        if (StringUtils.isNotEmpty(scopeuseUser)) {
            String scopeName = this.userApiService.getScopeName(scopeuseUser, corpId, TOKEN);
            result.put("scopeuseUserName", scopeName);
        }
        
        // 管理员
        String adminUserScope = popUserScopeUtilService.getScopeTypeValue("oa_meeting_apply_record_scope",
                "oa_meeting_boardroom_set", "admin_user_scope", StringUtils.null2String(boardroomSet.getAdminUserScope()));
        result.put("adminUserScope", adminUserScope);
        if (StringUtils.isNotEmpty(adminUserScope)) {
            String scopeName = this.userApiService.getScopeName(adminUserScope, corpId, TOKEN);
            result.put("adminUserName", scopeName);
        }

        //关联流程查询
        String progressId = StringUtils.null2String(boardroomSet.getProgressId());
        String progressName = "";
        if(!"".equals(progressId)){
            //流程列表
            List<Map<String,Object>> listMap = new ArrayList<Map<String,Object>>();
            Map<String,String> paramMap = new HashMap<String,String>();
            paramMap.put("userId", user.getUserId());
            paramMap.put("corpId", user.getCorpId());
            paramMap.put("groupId", user.getOrgId());
            paramMap.put("module", "meeting");
            paramMap.put("processName", "");
            try {
                String principalName = this.restClient.get("/bpm/process/getProcessList", user.getJwtToken(), paramMap);
                Map<String,Object> map = JsonUtils.readValue(principalName);
                if(map.get("type").toString().equals("success")){
                    listMap = (List<Map<String, Object>>) map.get("data");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            if(listMap!=null && listMap.size()>0) {
                for (Map<String, Object> map : listMap) {
                    if(StringUtils.null2String(map.get("bpmProcessDefineList")) != ""){
                        List<Map<String, Object>> bpmProcessDefineList = (List<Map<String, Object>>)map.get("bpmProcessDefineList");
                        for (Map<String, Object> progress: bpmProcessDefineList) {
                            if(progressId.equals(StringUtils.null2String(progress.get("code")))){
                                progressName = StringUtils.null2String(progress.get("name"));
                                break;
                            }
                        }
                    }
                }
            }
        }
        result.put("progressName", progressName);

        //查询会议室类型数据
        BoardroomCategorySet bcs = this.boardroomCategorySetService.findOne(boardroomSet.getCategoryId());
        String categoryName = "";
        if(bcs!=null){
            categoryName = bcs.getName();
        }
        //查看会议服务数据
        String serveName = "";
        if(StringUtils.isNotEmpty(boardroomSet.getMeetingServe())){
            List<ServeSet> serveList = this.serveSetService.getServeSetListByIds(boardroomSet.getMeetingServe());
            if(serveList!=null && serveList.size()>0){
                for(ServeSet s : serveList){
                    serveName += s.getName() +  ",";
                }
                serveName = serveName.substring(0,(serveName.length()-1));
            }
        }
        result.put("categoryName", categoryName);
        result.put("serveName", serveName);
        if(logService.checkOptLog(corpId, "meetingLog:room:03", user.getJwtToken()))//判断是否记录日志
        	this.logService.saveModuleLog("meetingLog:room:03", boardroomSet.getName(), "");//记录日志
        return result;
    }
    
    /**
     * 删除（批量）数据
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @RequiresPermissions({"meeting:room:04"})
    public OperationResult delete(HttpServletRequest request, @RequestParam("ids") String... ids) {
    	WebUser user = WebUtils.getCurrentUser();
    	boolean canLog = logService.checkOptLog(user.getCorpId(), "meetingLog:room:04", user.getJwtToken());//判断是否记录日志
    	List<BoardroomSet> list = null;
    	if(canLog) list = this.service.findAll(ids);
    	//判断会议类型是否已被使用
    	String msg = this.service.checkDeleteData(ids);
    	if(StringUtils.isNotEmpty(msg)){
    		return OperationResult.buildFailureResult(msg);
    	}
    	//记录日志
    	if(canLog && CollectionUtils.isNotEmpty(list)) {
    		List<Map<String, String>> operateDataList = new ArrayList<>();
    		for(BoardroomSet bs : list) {
    			Map<String, String> operateDataMap = new HashMap<>();
				// 操作数据
				operateDataMap.put("operateData", bs.getName());
				// 操作明细
				operateDataMap.put("operateDetails", "");
				// 请求Id
				operateDataMap.put("requestId", null);
				operateDataList.add(operateDataMap);
    		}
    		MeetingUtils.execute(()->{
    			// 记录批量日志
        		logService.batchSaveModuleLog("meetingLog:room:04", operateDataList, request);
    		});
    		
    	}
        return super.delete(ids);
    }
    
    /**
     * 查询会议室设置树数据
     * 
     * @return
     */
    @RequestMapping(value = "/getBoardroomTreeData", method = RequestMethod.GET)
    public OperationResult getBoardroomTreeData(HttpServletRequest request) {
        WebUser user = WebUtils.getCurrentUser();
        String corpId = user.getCorpId();
        String jeson = this.service.getBoardroomTreeData(corpId);
        return OperationResult.buildSuccessResult("", jeson);
    }

    /** 获取可使用会议室列表
     * @author zhaoyh
     * @date 2018年3月11日 下午5:38:39
     */
    @RequestMapping(value = "/getBoardroomTree", method = RequestMethod.GET)
    public OperationResult getBoardroomTree(HttpServletRequest request) {
        Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(request);
        WebUser user = WebUtils.getCurrentUser();
        String corpId = user.getCorpId();
        String userId = user.getUserId();

        //获取可用会议室
        StringBuffer str = new StringBuffer("");
        str.append("[");
        List<Map> rooms = this.service.getBoardroomData(corpId);
        
        List<Map> roomsNew = new ArrayList<Map>();
        
        if(CollectionUtils.isNotEmpty(rooms)) {
        	List<String> aScopeList = null;
        	String scopeuseUser = "";
         	for(Map m : rooms) {
         		
         		scopeuseUser = m.get("scopeuse_user")+"";
         		LOGGER.debug("-scopeuseUser:"+scopeuseUser);
         		
         		if(scopeuseUser!=null&&!"".equals(scopeuseUser)&&!"null".equals(scopeuseUser)) {
	         		aScopeList = new ArrayList<>();
	                aScopeList.add(scopeuseUser);
	                List<MeetingScope> scopeuseUserList = this.meetingScopeService.getMeetingScopeList("oa_meeting_boardroom_set", "scopeuse_user", aScopeList,true);
	                
	                if(scopeuseUserList!=null && scopeuseUserList.size()>0){
	                	List<String> unitUserList = null;
	                    for(MeetingScope ms : scopeuseUserList){
	                        String scopeValue = ms.getScopevalue();
	                        String scopeType = ms.getScopetype();
	                        if("user".equals(scopeType)){
	                        	if(userId.equals(scopeValue)) {
	                        		roomsNew.add(m);
	                        		break;
	                        	}
	                        }else if("org".equals(scopeType)){
	                        	unitUserList = this.userApiService.getUserIdsByOrgId(scopeValue, "", "1", corpId, TOKEN);
	                        	if(compareUserId(unitUserList,userId)){
	                        		roomsNew.add(m);
	                        		break;
	                        	}
	                        }else if("group".equals(scopeType)){
	                        	unitUserList = this.userApiService.getUserIdsByGrpId(scopeValue, "1", corpId, TOKEN);
	                        	if(compareUserId(unitUserList,userId)){
	                        		roomsNew.add(m);
	                        		break;
	                        	}
	                        }else if("station".equals(scopeType)){
	                        	unitUserList = this.userApiService.getUserIdsByStationId(scopeValue, "1", corpId, TOKEN);
	                        	if(compareUserId(unitUserList,userId)){
	                        		roomsNew.add(m);
	                        		break;
	                        	}
	                        }
	                    }
	                }
         		}else {
         			roomsNew.add(m);
         		}

         	}
        }
        
        if(roomsNew!=null && roomsNew.size()>0){
            for (Map<String, String> map: roomsNew) {
                str.append((new StringBuilder()).append("{\"id\":\"").append(map.get("id"))
                        .append("\",\"pId\":\"").append("\",\"name\":\"").append(map.get("name"))
                        .append("\",\"isApprove\":\"").append(map.get("is_approve"))
                        .append("\",\"beforeDays\":\"").append(StringUtils.null2String(map.get("beforeDays")))
                        .append("\",\"progressCode\":\"").append(map.get("progress_id")).append("\"},"));
            }
        }
        String result = str.toString();
        if (result.endsWith(",")){
            result = result.substring(0, result.length() - 1);
        }
        result = (new StringBuilder()).append(result).append("]").toString();
        return OperationResult.buildSuccessResult("", result);
    }
    
    /**
     * 查询会议室管理员
     * 
     * @return
     */
    @RequestMapping(value = "/getBoardroomAdmin", method = RequestMethod.GET)
    public List<Map<String, Object>> getBoardroomAdmin(HttpServletRequest request) {
    	//会议室管理员
    	WebUser user = WebUtils.getCurrentUser();
        String corpId = user.getCorpId();
        String boardroomId = StringUtils.null2String(request.getParameter("boardroomId"));
        List<Map<String, Object>> list = this.service.getBoardroomAdmin(boardroomId, corpId, TOKEN);
    	return list;
    }
    
    /**
     * 新建会议时查看会议室
     * 
     * @return
     */
    @RequestMapping(value = "/boardroomsView", method = RequestMethod.GET)
    public OperationResult boardroomsView(HttpServletRequest request) {
    	String corpId = WebUtils.getCurrentUser().getCorpId();
    	String userId = WebUtils.getCurrentUser().getUserId();
    	String isSearch = ValidateUtils.filter(request.getParameter("isSearch"));
    	List<Map> bsList = null;
    	String boardroomName = null, categoryId = null, count = null, meetingServe = null, address = null;
        if("1".equals(isSearch)) {//查询       
         	boardroomName = request.getParameter("boardroomName");
         	categoryId = request.getParameter("categoryId");
         	count = request.getParameter("count");
         	meetingServe = request.getParameter("meetingServe");
         	address = request.getParameter("address");
        }else {
        	String cateId = ValidateUtils.filter(request.getParameter("cateId"));
        	if(StringUtils.isEmpty(cateId)) {
        		List<BoardroomCategorySet> bcsList = this.boardroomCategorySetService.getCategorySetList(corpId);
        		if(CollectionUtils.isNotEmpty(bcsList)) cateId = bcsList.get(0).getId();
        	}
        	categoryId = cateId;
        }
        String cateAll = ValidateUtils.filter(request.getParameter("cateAll"));
        if("1".equals(cateAll)) {
        	categoryId = "";
        }
        bsList = this.service.getBoardroomInfoList(boardroomName, categoryId, count, meetingServe, address, corpId);
        
        List<Map> bsListNew = new ArrayList<Map>();
        
        if(CollectionUtils.isNotEmpty(bsList)) {
        	List<String> aScopeList = null;
        	String scopeuseUser = "";
         	for(Map m : bsList) {
         		
         		scopeuseUser = m.get("scopeuseUser")+"";
         		LOGGER.debug("-scopeuseUser:"+scopeuseUser);
         		
         		if(scopeuseUser!=null&&!"".equals(scopeuseUser)&&!"null".equals(scopeuseUser)) {
	         		aScopeList = new ArrayList<>();
	                aScopeList.add(scopeuseUser);
	                List<MeetingScope> scopeuseUserList = this.meetingScopeService.getMeetingScopeList("oa_meeting_boardroom_set", "scopeuse_user", aScopeList,true);
	                
	                if(scopeuseUserList!=null && scopeuseUserList.size()>0){
	                	List<String> unitUserList = null;
	                    for(MeetingScope ms : scopeuseUserList){
	                        String scopeValue = ms.getScopevalue();
	                        String scopeType = ms.getScopetype();
	                        if("user".equals(scopeType)){
	                        	if(userId.equals(scopeValue)) {
	                        		bsListNew.add(m);
	                        		break;
	                        	}
	                        }else if("org".equals(scopeType)){
	                        	unitUserList = this.userApiService.getUserIdsByOrgId(scopeValue, "", "1", corpId, TOKEN);
	                        	if(compareUserId(unitUserList,userId)){
	                        		bsListNew.add(m);
	                        		break;
	                        	}
	                        }else if("group".equals(scopeType)){
	                        	unitUserList = this.userApiService.getUserIdsByGrpId(scopeValue, "1", corpId, TOKEN);
	                        	if(compareUserId(unitUserList,userId)){
	                        		bsListNew.add(m);
	                        		break;
	                        	}
	                        }else if("station".equals(scopeType)){
	                        	unitUserList = this.userApiService.getUserIdsByStationId(scopeValue, "1", corpId, TOKEN);
	                        	if(compareUserId(unitUserList,userId)){
	                        		bsListNew.add(m);
	                        		break;
	                        	}
	                        }
	                    }
	                }
         		}else {
         			bsListNew.add(m);
         		}

         	}
        }
        
    	List<Map<String,Object>> list = this.service.getBoardroomDatas(bsListNew, corpId);
    	return OperationResult.buildSuccessResult(list);
    }
    
   private boolean compareUserId(List<String> unitUserList,String userId) {
    	
    	if(CollectionUtils.isNotEmpty(unitUserList)){
           for (String uid:unitUserList) {
        	  if (userId.equals(uid)) {
        		return true;
        	  }
          }
    	}
    	return false;
    	
    }

    /**   查询发送流程列表
     * @author zhaoyh
     * @date 2018年3月11日 下午5:38:39
     */
    @RequestMapping(value = "/getMeetingProcessTree", method = RequestMethod.GET)
    public OperationResult getMeetingProcessList(HttpServletRequest request) {
        Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(request);
        String search = request.getParameter("search");
        WebUser user = WebUtils.getCurrentUser();
        String corpId = user.getCorpId();

        //流程列表
        List<Map<String,Object>> listMap = new ArrayList<Map<String,Object>>();
        Map<String,String> paramMap = new HashMap<String,String>();
        paramMap.put("userId", user.getUserId());
        paramMap.put("corpId", user.getCorpId());
        paramMap.put("groupId", user.getOrgId());
        paramMap.put("module", "meeting");
        paramMap.put("processName", search);
        try {
            String principalName = this.restClient.get("/bpm/process/getProcessList", user.getJwtToken(), paramMap);
            Map<String,Object> map = JsonUtils.readValue(principalName);
            if(map.get("type").toString().equals("success")){
                listMap = (List<Map<String, Object>>) map.get("data");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        StringBuffer str = new StringBuffer("");
        str.append("[");
        if(listMap!=null && listMap.size()>0){
            for (Map<String, Object> map: listMap) {
                if(StringUtils.null2String(map.get("bpmProcessDefineList")) != ""){
                    List<Map<String, Object>> bpmProcessDefineList = (List<Map<String, Object>>)map.get("bpmProcessDefineList");
                    for (Map<String, Object> progress: bpmProcessDefineList) {
                        str.append((new StringBuilder()).append("{\"id\":\"").append(StringUtils.null2String(progress.get("code")))
                                .append("\",\"pId\":\"").append("\",\"name\":\"").append(StringUtils.null2String(progress.get("name")))
                                .append("\"},"));
                    }
                }
            }
        }

        String result = str.toString();
        if (result.endsWith(",")){
            result = result.substring(0, result.length() - 1);
        }
        result = (new StringBuilder()).append(result).append("]").toString();
        return OperationResult.buildSuccessResult("", result);
    }
}
